﻿using ManagementCMS.Tool;
using ManagementCMS.Tool.Log4;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.TenPayLibV3;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Weixin.Core.config;
using Weixin.Core.Model;

namespace Weixin.Core
{

    /// <summary>
    /// 统一订单帮助类
    /// </summary>
    public class UnifiedOrder
    {

        /// <summary>
        /// 微信H5统一下单
        /// </summary>
        /// <param name="payOrder"></param>
        /// <returns></returns>
        private static TenPayV3UnifiedorderRequestData PayH5Model(PayOrder payOrder)
        {

            string nonceStr = TenPayV3Util.GetNoncestr();
            int totalFee = UtilsBase.ObjToInt(payOrder.PayMoney*100, 0); 

            return new TenPayV3UnifiedorderRequestData(
                WxConfig.AppId,
                WxConfig.MchId,
                payOrder.OrderName,
                payOrder.OrderNo,
                totalFee,
                "",
                payOrder.NotifyUrl,
                TenPayV3Type.JSAPI,
                payOrder.OpenId,
                WxConfig.Key,
                nonceStr,
                "",
                payOrder.TimeStart,
                payOrder.TimeExpire,
                payOrder.OrderName,
                "",
                "CNY",
                "",
                WxAuxiliary.GetOrderNumber(""),
                false
                );
        }


        /// <summary>
        /// 获取统一下单接口是否返回成功
        /// </summary>
        /// <param name="payOrder"></param>
        /// <returns></returns>
        public static WxOrderResult GetH5OrderResult(PayOrder payOrder)
        {

            WxOrderResult orderResult = new WxOrderResult();

            try
            {
                var tenPayV3 = PayH5Model(payOrder);
                var unifiedOrder = TenPayV3.Unifiedorder(tenPayV3);
                if (unifiedOrder.IsResultCodeSuccess())
                {

                    orderResult.prepay_id = unifiedOrder.prepay_id;
                    orderResult.noncestr = TenPayV3Util.GetNoncestr();
                    orderResult.timestamp = TenPayV3Util.GetTimestamp();
                    orderResult.paysign = TenPayV3.GetJsPaySign(WxConfig.AppId, orderResult.timestamp,
                        orderResult.noncestr, string.Format("prepay_id={0}", orderResult.prepay_id),
                        WxConfig.Key);
                }

                orderResult.return_code = unifiedOrder.return_code;
                orderResult.result_code = unifiedOrder.result_code;
            }
            catch (Exception ex)
            {
                Log4Helper.WriteError("下单失败",ex);
            }


            return orderResult;
        }






    }

}
